<template>
    <div class="chapter-set">
        <el-tabs v-model="activeName" type="border-card">
            <el-tab-pane
                v-for="(tabItem, tabIndex) in tabs"
                :key="tabItem.name"
                :label="tabItem.title"
                :name="tabItem.name"
            >
                <el-card v-for="(item,index) in chapterContents" :key="index">
                    <div slot="header" class="clearfix">
                        <span v-if="activeName === 'cn'">{{getLargeFormat(index+1)}} {{item.name}}</span>
                        <span v-if="activeName === 'en'">{{(index+1)}}、 {{item.nameEn}}</span>
                        <div  v-if="item.contentType === 0 && isEdit" style="float: right;">
                            <el-button
                                style="padding: 3px 0"
                                type="text"
                                v-if="type == 2"
                                @click="beforeCopye(index)"
                            >复制之前</el-button>
                            <el-button
                                style="padding: 3px 0"
                                type="text"
                                @click="uploadClick(index)"
                            >上传图片</el-button>
                        </div>
                        <el-button
                            @click="tableClick(index)"
                            v-if="item.contentType === 1 && isEdit"
                            style="float: right; padding: 3px 0"
                            type="text"
                        >关联表格</el-button>
                    </div>
                    <div v-if="item.contentType===0">
                        <div
                            :contenteditable="isEdit"
                            v-show="activeName==='cn'"
                            v-html="item.content"
                            :ref="'content'+index"
                            @blur="saveChapter"
                        ></div>
                        <div
                            :contenteditable="isEdit"
                            v-show="activeName==='en'"
                            :ref="'contentEn'+index"
                            v-html="item.contentEn"
                            @blur="saveChapter"
                        ></div>
                    </div>
                    <div v-else>
                        <div
                            v-show="activeName==='cn'"
                            @blur="saveChapter"
                            v-html="item.minorDetailTable?item.minorDetailTable.contentBefore:''"
                        ></div>
                        <div
                            v-show="activeName==='en'"
                            @blur="saveChapter"
                            v-html="item.minorDetailTable?item.minorDetailTable.contentBeforeEn:''"
                        ></div>
                        <course-type
                            v-if="item.minorDetailTable && item.minorDetailTable.table === 1"
                            :templateId="templateId"
                            :operationFlag="false"
                            :type="type"
                        />

                        <minor-table
                            v-if="item.minorDetailTable && item.minorDetailTable.table === 2"
                            :templateId="templateId"
                            :operationFlag="false"
                            :advancedType="advancedType"
                            :schoolTerm="schoolTerm"
                            :type="type"
                        ></minor-table>
                        <div
                            v-show="activeName==='cn'"
                            @blur="saveChapter"
                            v-html="item.minorDetailTable?item.minorDetailTable.contentAfter:''"
                        ></div>
                        <div
                            v-show="activeName==='en'"
                            @blur="saveChapter"
                            v-html="item.minorDetailTable?item.minorDetailTable.contentAfterEn:''"
                        ></div>
                    </div>
                </el-card>
            </el-tab-pane>
        </el-tabs>
        <upload-img v-if="isEdit" :size="5" ref="editor" @successCBK="successCBK" :pictureTip="imgOption.pictureTip" :type="imgOption.type"/>
        <edu-dialog
            title="复制之前"
            size="small" 
            :visible.sync="copyVisible"
            :confirmBtnText="$t('common.btn.confirm')" 
            v-if="copyVisible"
            :close-on-click-modal="false" 
            @close="copyClose" 
            @confirm="copyConfirm">
                <el-form
                    ref="copyForm"
                    :model="copyForm"
                    label-width="120px"
                    label-position="right"
                >
                    <el-row :gutter="20">
                        <el-col :span="18">
                            <el-form-item label="辅修年级:" prop="minorGrade"> 
                                <el-date-picker
                                    v-model="copyForm.minorGrade"
                                    type="year"
                                    clearable
                                    value-format="yyyy"
                                    style="width: 100%"
                                    @change="changeGrade"
                                    placeholder="请选择"
                                ></el-date-picker>
                            </el-form-item>
                        </el-col>
                        <!-- <el-col :span="18">
                            <el-form-item :label="$t('minor.major.college') + ':'" prop="collegeCode">
                                <el-select
                                    v-model="copyForm.collegeCode"
                                    @change="getProfession"
                                    style="width: 100%"
                                >
                                    <el-option
                                        v-for="item in copyOptions.collegeCode"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col> -->
                        <!-- <el-col :span="18">
                            <el-form-item label="辅修专业:" prop="profession">
                                <el-select
                                    v-model="copyForm.profession"
                                    style="width: 100%"
                                >
                                    <el-option
                                        v-for="item in copyOptions.profession"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col> -->
                        <el-col :span="18">
                            <el-form-item label="培养方案:" prop="schemId">
                                <el-select
                                    v-model="copyForm.schemId"
                                    @change="changeScheme"
                                    clearable
                                    style="width: 100%"
                                >
                                    <el-option
                                        v-for="item in copyOptions.schemOption"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="18">
                            <el-form-item label="章节:" prop="chapterId">
                                <el-select
                                    v-model="copyForm.chapterId"
                                    style="width: 100%"
                                    clearable
                                >
                                    <el-option
                                        v-for="item in copyOptions.chapters"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
        </edu-dialog>
    </div>
</template>

<script>
import MinorTable from "./MinorTable";
import CourseType from "./CourseType";
import UploadImg from "common/src/components/common/UploadImg";
import RelationTable from "./RelationTable";
import {
    getChapterTemplete,
    saveChapter
} from "common/src/api/minor/minorCulturePlanManager";
// import UTILS from "common/src/utils/utils";
// import { queryDic } from "common/src/api/dictionary";
import {findCultureSchemeListByYear, findCultureSchemeDetailList} from "common/src/api/minor/minorCultureScheme";
export default {
    name: "ChapterSet",
    components: { MinorTable, RelationTable, UploadImg, CourseType },
    props: {
        templateId: {
            type: Number,
            default: 0
        },
        type: {
            default: 1,
            type: Number
        },
        courseTyleData: {
            type: Array,
            default: []
        },
        isEdit: {
            type: Boolean,
            default: true
        },
        advancedType: {
            default: '',
            type: String
        },
        schoolTerm: {
            default: 6,
            type: Number
        }
    },
    data() {
        return {
            tabs: [
                {
                    title: "填写章节样例（中文）",
                    name: "cn"
                },
                {
                    title: "填写章节样例（英文）",
                    name: "en"
                }
            ],
            activeName: "cn",
            dialogShow: false,
            chapterContents: [],
            updataIndex: 0,
            copyVisible: false,
            copyForm: {
                minorGrade:'',
                schemId: '',
                chapterId: '',
                index: ''
            },
            copyOptions: {
                schemOption: [],
                chapters: []
            },
            imgOption:{
                pictureTip: '上传图片支持jpg、jpeg、png、bmp、gif格式，且单个不大于5M',
                type: ["image/jpg", "image/jpeg", "image/png", "image/bmp", "image/gif"]
            }
        };
    },
    mounted() {
        this.getTemplate();
        // if (this.type == 2) {
        //     this.getOptions();
        // }
    },
    methods: {
        getTemplate() {
            let params = {
                templateId: this.templateId,
                type: this.type
            };
            if (this.type == "2") {
                params = {
                    cultureId: this.templateId,
                    type: this.type
                };
            }
            getChapterTemplete(params).then(({ code, data }) => {
                if (code === 200) {
                    this.chapterContents = data.chapterContents;
                }
            });
        },
        getLargeFormat(num, suffix = "、") {
            const value = Number(num);
            if (!isNaN(value)) {
                let result = "";
                const char = [
                    "一",
                    "二",
                    "三",
                    "四",
                    "五",
                    "六",
                    "七",
                    "八",
                    "九"
                ];
                if (value > 0 && value < 10) {
                    result = char[value - 1];
                } else if (value >= 10 && value < 100) {
                    if (Math.floor(value / 10) === 1) {
                        result += "十";
                    } else {
                        result += char[Math.floor(value / 10) - 1] + "十";
                    }
                    if (value % 10 > 0) {
                        result += char[(value % 10) - 1];
                    }
                }
                return result + suffix;
            } else {
                return "";
            }
        },
        uploadClick(index) {
            this.updataIndex = index;
            this.$refs.editor.dialogVisible = true;
        },
        tableClick(index) {
            this.$emit("tableClick", this.chapterContents[index]);
        },
        successCBK(arr) {
            // 图片上传后返回的图片数组
            let vHtml = "";
            arr.forEach(el => {
                vHtml += `<img src="${el.url}" width = "${el.width}" height ="${
                    el.height
                }" />`;
            });
            if (this.activeName === "cn") {
                this.$refs[`content${this.updataIndex}`][0].innerHTML += vHtml;
            } else {
                this.$refs[
                    `contentEn${this.updataIndex}`
                ][1].innerHTML += vHtml;
            }
            this.$refs.editor.dialogVisible = false;
            this.saveChapter();
        },
        formatTags(str) {
            let reg = /(<(img|br)[^<>]*)(>)/g; 
            return (str || '').replace(reg, "$1/$3");
        },
        saveChapter(flag) {
            let params = {};
            if (this.chapterContents.length == 0) {
                this.$message({
                    message: "保存成功",
                    type: "success"
                });
                this.$emit("saveSuccess", true, flag);
                return;
            }
            params.minorCultureSchemeDetails = this.chapterContents.map(
                (el, index) => {
                    if (el.contentType === 0) {
                        el.content = this.formatTags(this.$refs[`content${index}`][0].innerHTML);
                        el.contentEn = this.formatTags(this.$refs[`contentEn${index}`][1].innerHTML);
                    }
                    return el;
                }
            );
            params.type = this.type;
            if (this.type == "2") {
                params.cultureId = this.templateId;
            } else {
                params.templateId = this.templateId;
            }

            saveChapter(params).then(({ code }) => {
                if (code === 200) {
                    this.$refs.editor.dialogVisible = false;
                    this.$message({
                        message: "保存成功",
                        type: "success"
                    });
                    this.getTemplate();
                    this.$emit("saveSuccess", true, flag);
                } else {
                    this.$emit("saveSuccess", false, flag);
                }
            });
        },
        beforeCopye(index) {
            this.copyForm = {
                minorGrade:'',
                schemId: '',
                chapterId: '',
                index: index
            }
            this.copyOptions.schemOption = [];
            this.copyOptions.chapters = [];
            this.copyVisible = true;
        },
        copyClose() {
            this.copyVisible = false;
        },
        copyConfirm() {
            let index =  this.copyForm.index;
            let content = this.copyForm.chapterId;
            if (content) {
                if (this.activeName == 'en') {
                    this.$refs[`contentEn${index}`][1].innerHTML = content;
                }else {
                    this.$refs[`content${index}`][0].innerHTML = content;
                }
            }
            this.saveChapter();
            this.copyClose();
        },
        async changeGrade() {
             let params = {
                minorGrade: this.copyForm.minorGrade,
                cultureId: this.templateId
            };
            if (!params.minorGrade) {
                return;
            }
            this.copyForm.schemId = "";
            this.copyOptions.schemOption = [];
            this.changeScheme();
            let {code, data} = await findCultureSchemeListByYear(params);
            if (code == 200) {
                this.copyOptions.schemOption = (data || []).map(item => ({
                    label: item.name,
                    key: item.id,
                    value: item.id
                }))
            }
        },
        async changeScheme() {
            this.copyForm.chapterId = "";
            this.copyOptions.chapters = [];
            if (!this.copyForm.schemId) {
                return;
            }
            let param = {cultureId: this.copyForm.schemId}
            let {code, data} = await findCultureSchemeDetailList(param);
            if (code == 200) {
                let isEn = this.activeName == 'en';
                this.copyOptions.chapters = (data || []).map(item => ({
                    label:  isEn ? item.nameEn: item.name,
                    key: item.id,
                    value: isEn ?  item.contentEn :item.content
                }));
            }
        }
    }
};
</script>

<style lang="scss" scoped>
</style>
